package com.contract.spirit.ui.withdraw

import android.content.Context
import android.content.Intent
import android.widget.CheckBox
import com.contract.commonlib.util.ext.setOnSingleClickListener
import com.contract.commonlib.base.BaseActivity
import com.contract.commonlib.http.ext.parseState
import com.contract.commonlib.util.ext.showToast
import com.contract.spirit.R
import com.contract.spirit.bean.response.WithDrawResponse
import com.contract.spirit.databinding.ActivityWithdrawCoinBinding
import com.contract.spirit.func.callback.OnPayListener
import com.contract.spirit.func.dialog.InputPayPasswordDialog
import com.contract.spirit.manage.CheckBoxManager
import com.contract.spirit.manage.CommonConfigManager
import com.contract.spirit.manage.LiveDataEventManager
import com.contract.spirit.ui.password.SetPasswordActivity
import com.jeremyliao.liveeventbus.LiveEventBus
import java.math.BigDecimal

/**
 * @author: witness
 * created: 2021/9/29
 * desc: 提币
 */
class WithdrawCoinActivity : BaseActivity<ActivityWithdrawCoinBinding, WithDrawViewModel>() {
    private var coinErcAddressValue: String = ""
    private var coinTrcAddressValue: String = ""
    private var selectPosition: Int = 0

    override fun setContentView(): Int {
        return R.layout.activity_withdraw_coin
    }

    override fun initData() {
        getWithDrawConfig()
        initWitDrawType()
        mBinding.apply {
            userInfo = CommonConfigManager.userInfoResponse
            mViewModel.coinAddressValue.set("")
            viewModel = mViewModel
            tvGetCode.setOnSingleClickListener {
                getEmsCode()
            }
            btnWithdraw.setOnSingleClickListener {
                startWitDraw()
            }
            tvAll.setOnSingleClickListener {
                mViewModel.coinNumValue.set(CommonConfigManager.userInfoResponse.unCashAmount)
            }
        }
    }

    override fun onReload() {
        mViewModel.withDrawConfigRes.value = null
        getWithDrawConfig()
    }

    private fun startWitDraw() {
        val minAmount: String = if (selectPosition == 0) {
            withDrawResponse.cashData.cash_ERC20_min_quantity
        } else {
            withDrawResponse.cashData.cash_TRC20_min_quantity
        }
        when {
            BigDecimal(
                mViewModel.coinNumValue.get().toString()
            ) > BigDecimal(CommonConfigManager.userInfoResponse.unCashAmount) -> {
                showToast("可提现余额不足")
            }
            BigDecimal(mViewModel.coinNumValue.get().toString()) < BigDecimal(minAmount) -> {
                showToast("提现数量不能小于$minAmount USDT")
            }
            else -> {
                if (CommonConfigManager.userInfoResponse.isSetPassword()) {
                    InputPayPasswordDialog.showDialog(mContext, object : OnPayListener {
                        override fun startPay(code: String) {
                            mViewModel.startWithDraw(
                                getSelectWithDrawType(), mBinding.tvRealNum.text.toString(), code
                            )
                        }
                    })
                } else {
                    SetPasswordActivity.launch(mContext)
                }
            }
        }
    }

    override fun registerNecessaryObserver() {
        super.registerNecessaryObserver()
        onEmsCodeObserve()
        onWithDrawConfigObserve()
        onWithDrawSuccessObserve()
    }


    private fun onWithDrawSuccessObserve() {
        mViewModel.withdrawSuccessRes.observe(this, {
            parseState(it, {
                finish()
                LiveEventBus.get<String>(LiveDataEventManager.WITHDRAW_SUCCESS)
                    .post("cashSuccess")
                WithdrawSuccessActivity.launch(mContext)
            })
        })
    }

    lateinit var withDrawResponse: WithDrawResponse
    private fun onWithDrawConfigObserve() {
        mViewModel.withDrawConfigRes.observe(this, { it ->
            parseState(it, {
                mBinding.withdrawInfo = it.cashData
                mViewModel.cashFee.set(it.cashData.cash_ERC20_fee)
                mViewModel.cashMinQuantity.set(it.cashData.cash_ERC20_min_quantity)
                withDrawResponse = it
            })
        })
    }

    private fun onEmsCodeObserve() {
        mViewModel.emsCodeObserve.observe(this, {
            parseState(it, {
                mBinding.tvGetCode.start()
            })
        })
    }

    private fun initWitDrawType() {
        val withDrawTypeList: ArrayList<String> = ArrayList()
        withDrawTypeList.add("ERC20")
        withDrawTypeList.add("TRC20")
        mBinding.apply {
            vgCashType.removeAllViews()
            val cpTypeCheckBox: ArrayList<CheckBox> = ArrayList()
            for (i in 0 until withDrawTypeList.size) {
                val typeDesc = withDrawTypeList[i]
                val checkBox = CheckBoxManager.getCheckBox(mContext, typeDesc)
                checkBox?.apply {
                    isChecked = i == 0
                    tag = typeDesc
                    cpTypeCheckBox.add(checkBox)
                }
            }
            vgCashType.setCheckBoxs(cpTypeCheckBox)
            vgCashType.registerChangeListener {
                withDrawResponse.cashData.apply {
                    if (it == 0) {
                        coinTrcAddressValue = mViewModel.coinAddressValue.get().toString()
                        mViewModel.coinAddressValue.set(coinErcAddressValue)
                        mViewModel.cashFee.set(cash_ERC20_fee)
                        mViewModel.cashMinQuantity.set(cash_ERC20_min_quantity)
                    } else {
                        coinErcAddressValue = mViewModel.coinAddressValue.get().toString()
                        mViewModel.coinAddressValue.set(coinTrcAddressValue)
                        mViewModel.cashFee.set(cash_TRC20_fee)
                        mViewModel.cashMinQuantity.set(cash_TRC20_min_quantity)
                    }
                }
                selectPosition = it
            }
        }
    }

    private fun getSelectWithDrawType(): String {
        val checked: List<CheckBox> = mBinding.vgCashType.checked
        if (checked.isNotEmpty()) {
            val checkBox = checked[0]
            return checkBox.tag as String
        }
        return ""
    }

    private fun getWithDrawConfig() {
        mViewModel.getWithDrawConfig()
    }

    private fun getEmsCode() {
        mViewModel.getEmsCode()
    }

    companion object {
        fun launch(mContext: Context) {
            mContext.startActivity(Intent(mContext, WithdrawCoinActivity::class.java))
        }
    }
}